package com.erac.odyssey.webservice.ota;

import java.util.Set;

import javax.xml.namespace.QName;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPMessage;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext; 

public class AddAuthHandler implements SOAPHandler<SOAPMessageContext> {  
    
    @Override  
    public boolean handleMessage(SOAPMessageContext context) {  
        // 判断消息是请求还是响应  
        Boolean output = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);  
  
        SOAPMessage message = context.getMessage();  
  
        if (output) {  
            try {  
                SOAPHeader header = message.getSOAPHeader();  
                if (header == null) {  
                    header = message.getSOAPPart().getEnvelope().addHeader();  
                }  
  
                SOAPElement auth = header.addChildElement(new QName("https://cis1-xmldirect.ehi.com/services30/OTA30SOAP", "auth"));  
                  
                SOAPElement name = auth.addChildElement("name");  
                name.addTextNode("OTA_CNHLTRTST1");  
  
                SOAPElement password = auth.addChildElement("password");  
                password.addTextNode("hZ96nB3h");  
                  
                message.saveChanges();  
  
            } catch (SOAPException e) {  
                e.printStackTrace();  
            }  
        }  
          
        System.out.println(output ? "客户端请求：" : "客户端接收：");  
        try {  
            message.writeTo(System.out);  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
          
        System.out.println("\r\n");  
  
        return true;  
    }  
  
    @Override  
    public boolean handleFault(SOAPMessageContext context) {  
        return true;  
    }  
  
    @Override  
    public void close(MessageContext context) {  
    }  
  
    @Override  
    public Set<QName> getHeaders() {  
        return null;  
    }  
}  
